<template>
  <div>
    <el-tabs type="card" :value="tabValue" @tab-remove="removeTab" @tab-click="onClickTab" :style="{backgroundColor: '#FFF'}">
      <el-tab-pane
        v-if="showTabsRouter"
        v-for="(item,index) in showTabsRouter"
        :closable="item.isClear"
        :key="item.path"
        :name="item.path">
        <span slot="label"><i :class="item.icon"></i> {{item.name}}</span>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { mapMutations, mapGetters } from 'vuex'
import types from '../../../store/mutation-types'

export default {
  name: 'ZlRouterTabs',
  mounted () {
  },
  watch: {
    $route (to) {
      const tabObj = {
        path: to.path,
        name: to.name,
        isClear: to.meta.isClear,
        icon: to.meta.icon
      }
      this.onlyTabsRouter({...tabObj})
    }
  },
  data () {
    return {
      tabValue: ''
    }
  },
  computed: {
    showTabsRouter () {
      return this.$store.state.permission.tabsRouter
    }
  },
  methods: {
    // 增加无重复Router
    onlyTabsRouter (tabObj) {
      this.tabValue = tabObj.path
      let onlyFlag = this.showTabsRouter.some(item => {
        return item.path === tabObj.path
      })
      if (!onlyFlag) {
        console.log('增加无重复Router:', tabObj.path)
        if (tabObj.path !== '/main') {
          this.setTabsRouter(tabObj)
        }
      }
    },
    ...mapGetters({

    }),
    ...mapMutations({
      // 添加选择路由
      setTabsRouter: types.PERMISSION + types.FS + types.TABS_ROUTER,
      // 移除选择路由
      delTabsRouter: types.PERMISSION + types.FS + types.DEL_TABS_ROUTER
    }),
    // 关闭单个的路由导航
    removeTab (targetName) {
      console.log('关闭单个的路由导航-targetName:', targetName)
      const oldTabsRouter = this.$store.state.permission.tabsRouter
      let activeTabs = []
      let isDeTab = true
      let delTab = []
      oldTabsRouter.forEach(function (value, index, array) {
        if (array[index].path === targetName) {
          delTab = array[index]
          isDeTab = false
        } else {
          if (isDeTab) {
            activeTabs = array[index]
          }
        }
      })
      this.delTabsRouter(delTab)
      if (activeTabs.path) {
        this.tabValue = activeTabs.path
        this.$router.push(activeTabs.path)
      }
    },
    // 点击导航路由
    onClickTab (tab) {
      console.log('点击导航路由-onClickTab:', tab.name)
      const oldTabsRouter = this.$store.state.permission.tabsRouter
      let activeTabs = []
      oldTabsRouter.forEach(function (value, index, array) {
        if (array[index].path === tab.name) {
          activeTabs = array[index]
        }
      })
      if (activeTabs.path) {
        this.$router.push(activeTabs.path)
      }
    }
  }
}
</script>
